//
//  ZBLinkmanViewModel.m
//  BaseRACDemo
//
//  Created by Angel_Yan on 2018/3/27.
//  Copyright © 2018年 庄波. All rights reserved.
//

#import "ZBLinkmanViewModel.h"
#import "ZBLinkman.h"
#import "ZBLinkmanItemViewModel.h"


@interface ZBLinkmanViewModel ()

@property (nonatomic, readwrite , assign) bool isAllSelect;///< 全选

@end


@implementation ZBLinkmanViewModel


- (void)initialize {
    [super initialize];

    self.title = @"通讯录";
    //允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    //允许上啦加载
    self.shouldPullUpToLoadMore = NO;
    ///没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    self.style = UITableViewStylePlain;
    
    /// 挂数据
    @weakify(self);

    RAC(self, dataSource) = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        //若没有错误发送正确信息,并将数组送出
        [subscriber sendNext:[self fetchLocalData]];
        //正确信息发送完毕后发送完成信号,若信息为错误信息则不发送完成信号
        [subscriber sendCompleted];
        return nil;
    }];
    
    ///< 判断全选
    [[[RACObserve(self,arrSelect) skip:1] map:^id _Nullable(NSArray *mArr) {
        return mArr.count == self.dataSource.count ? @(1) : @(0);
    }] subscribeNext:^(NSNumber *x) {
        self.isAllSelect = [x boolValue];
    }];
        
    
    // 选中cell 跳转的命令
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath * indexPath) {
        @strongify(self);
        ZBLinkmanItemViewModel *viewModel = (ZBLinkmanItemViewModel *)self.dataSource[indexPath.row];
        NSMutableArray *mArr = @[].mutableCopy;
        [mArr addObjectsFromArray:self.arrSelect];
        if (viewModel.isSelect) {
            viewModel.isSelect = NO;
            [mArr removeObject:viewModel];
        } else {
            viewModel.isSelect = YES;
            [mArr addObject:viewModel];
        }
        self.arrSelect = mArr.copy;
        return [RACSignal empty];
    }];
}


- (NSArray *)fetchLocalData {
    ZBLinkman *linkman = [[ZBLinkman alloc] init];
    if (MHObjectIsNil(linkman) || linkman.arrLinkman.count == 0) {
        return @[];
    }
    NSArray *viewModels = [linkman.arrLinkman.rac_sequence map:^id _Nullable(ZBLinkmanItem * _Nullable value) {
        ZBLinkmanItemViewModel *itemViewModel = [[ZBLinkmanItemViewModel alloc] initWithLinkmanItem:value];
        return itemViewModel;
    }].array;
    return viewModels ?: @[];
}

@end
